package com.gitee.Jmysy.binlog4j.springboot.starter.example;


import com.gitee.Jmysy.binlog4j.core.*;
import com.gitee.Jmysy.binlog4j.core.config.RedisConfig;

import java.text.SimpleDateFormat;
import java.util.Date;

public class BootStrap {
    public static void main(String[] args) {
        /*RedisConfig redisConfig = new RedisConfig();
        redisConfig.setHost("127.0.0.1");
        redisConfig.setPort(6379);
        redisConfig.setPassword("123");
        redisConfig.setDatabase(15);*/
        BinlogClientConfig clientConfig = new BinlogClientConfig();
        //clientConfig.setRedisConfig(redisConfig); // Redis 配置
        //clientConfig.setPersistence(true); // 开启续读
        clientConfig.setHost("127.0.0.1");
        clientConfig.setPort(3306);
        clientConfig.setUsername("root");
        clientConfig.setPassword("root");
        clientConfig.setServerId(1270013306);

        IBinlogClient binlogClient = new BinlogClient(clientConfig);
        binlogClient.registerEventHandler(new IBinlogEventHandler() {
            @Override
            public void onInsert(long serverId, BinlogEvent event, long timestamp) {
                System.out.println(longTotime(timestamp)+"插入数据:{}"+serverId+event.getDatabase()+"->"+event.getData());
            }

            @Override
            public void onUpdate(long serverId, BinlogEvent event, long timestamp) {
                if(event.isUpdatePk()){
                    //更新了主键 兼容debezium计数
                    System.out.println(longTotime(timestamp)+"修改数据:{}"+serverId+event.getDatabase()+"->"+event.getData());
                    System.out.println("修改了主键数据"+event.isUpdatePk());
                }else {
                    System.out.println(longTotime(timestamp)+"修改数据:{}"+serverId+event.getDatabase()+"->"+event.getData());
                }
            }

            @Override
            public void onDelete(long serverId, BinlogEvent event, long timestamp) {
                System.out.println(longTotime(timestamp)+"删除数据:{}"+ serverId+event.getDatabase()+"->"+event.getData());
            }

            @Override
            public void onDDL(long serverId, String databaseName, String tableName, String sql, long timestamp) {
                System.out.println(longTotime(timestamp)+"DDL变动:{}"+ serverId+databaseName+"->"+tableName+sql);
            }

            @Override
            public boolean isHandle(long serverId, String database, String table) {

                return database.equals("db01")&&table.equals("pop_kpi_b");
            }


        });

        binlogClient.connect();
    }

    public static String longTotime(long timestamp) {
        Date date = new Date(timestamp);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }


}
